let isRightContextMenuShow = false;
let rightContextMenuDom = null;
let menuPosition = [0, 0]
let menuItemActionOptions = [];

function bindContextMenu() {
    // 监听右键点击事件  
    document.addEventListener('contextmenu', function (e) {
        e.preventDefault(); // 禁用默认的上下文菜单  
        showRightContextMenu(window.globel.lastMouseHoverNode, e);
        window.globel.lastMouseHoverNode = null;
    });
    document.addEventListener('click', function (e) {
        if (isRightContextMenuShow) {
            rightContextMenuDom.remove();
            isRightContextMenuShow = false;
        }
    });
}

function showRightContextMenu(selNode, e) {
    if (isRightContextMenuShow) {
        rightContextMenuDom.remove();
        isRightContextMenuShow = false;
    }
    if (!selNode) return;
    if (!e) {
        e = menuPosition;
    }
    var contentMenuDom = `
       <div class="menu-item" onclick="alert('你选择了选项1')">选项1</div>  
       <div class="menu-item" onclick="alert('你选择了选项2')">选项2</div>  
       <div class="menu-item" onclick="alert('你选择了选项3')">选项3</div>  
    `
    contentMenuDom = buildContextMenuItems(selNode);
    var dom = document.createElement('div');
    dom.className = "menu";
    dom.innerHTML = contentMenuDom;
    dom.style.top = e.pageY + 'px'; // 设置菜单位置  
    dom.style.left = e.pageX + 'px';
    dom.style.display = 'block'; // 显示自定义菜单  
    document.body.appendChild(dom);
    isRightContextMenuShow = true;
    rightContextMenuDom = dom;
}
function buildContextMenuItems(selNode) {
    window.globel.lastMouseHoverNode = selNode;
    var las = selNode.labels[0].split(':');

    var menuItems = [];
    if (las.length > 1) {
        var nodeType = las[1];
        if (nodeType == "AgSrvContent") {
            menuItemActionOptions.push(['Content2BuildingId', selNode.properties.contentId, selNode.properties.bldgId])
            menuItems.push(`<div class="menu-item" 
            onclick="runAction(`+ menuItems.length + `)">相同BuildingID</div> `)
        }
    }
    else {
        menuItems.push(`<div class="menu-item" 
            onclick="getNextNodes('`+selNode.id+`')">获得下一节点</div> `)
    }

    menuItemActionOptions = [];

    var allMenus = "";
    for (var i = 0; i < menuItems.length; i++) {
        allMenus += menuItems[i];
    }
    return allMenus;
}
function runAction(index) {
    let options = menuItemActionOptions[index];
    getSubRelationWithOptions(options[0], options[1], options[2]);

    if (isRightContextMenuShow) {
        rightContextMenuDom.remove();
        isRightContextMenuShow = false;
    }
}
bindContextMenu();